package com.pzhu.gmall.cart.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.pzhu.gmall.bean.OmsCartItem;
import com.pzhu.gmall.cart.mapper.OmsCartItemMapper;
import com.pzhu.gmall.service.CartService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import tk.mybatis.mapper.entity.Example;

/**
 * @author 刘鹏 liupeng
 * @date 2019/11/15
 **/
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private OmsCartItemMapper omsCartItemMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public OmsCartItem ifCartExistByUser(String memberId, String skuId) {
        Example example = new Example(OmsCartItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("memberId", memberId);
        criteria.andEqualTo("productSkuId", skuId);
        return omsCartItemMapper.selectOneByExample(example);
    }

    @Override
    public void addCart(OmsCartItem omsCartItem) {
        omsCartItemMapper.insert(omsCartItem);
    }

    @Override
    public void updateCart(OmsCartItem omsCartItemFromDb) {
        omsCartItemMapper.updateByPrimaryKeySelective(omsCartItemFromDb);
    }

    @Override
    public void flushCartCache(String memberId) {

        OmsCartItem omsCartItem = new OmsCartItem();
        omsCartItem.setMemberId(memberId);
        List<OmsCartItem> omsCartItems = omsCartItemMapper.select(omsCartItem);
        // 同步到redis缓存中
        Map<String, String> map = new HashMap<>();
        for (OmsCartItem cartItem : omsCartItems) {
            map.put(cartItem.getProductSkuId(), JSON.toJSONString(cartItem));
        }
        try {
            stringRedisTemplate.opsForHash().delete("user:" + memberId + ":cart");
        } catch (Exception e) {

        }

        stringRedisTemplate.opsForHash().putAll("user:" + memberId + ":cart", map);
    }

    @Override
    public List<OmsCartItem> cartItemList(String userId) {
        List omscaStrList = stringRedisTemplate.opsForHash().values("user:" + userId + ":cart");
        List<OmsCartItem> cartItems = new ArrayList<>();
        omscaStrList.stream().forEach(s -> {
            cartItems.add(JSON.parseObject((String) s, OmsCartItem.class));
        });
        return cartItems;
    }

    @Override
    public void checkCart(OmsCartItem omsCartItem) {
        Example e = new Example(OmsCartItem.class);

        e.createCriteria().andEqualTo("memberId",omsCartItem.getMemberId()).andEqualTo("productSkuId",omsCartItem.getProductSkuId());

        omsCartItemMapper.updateByExampleSelective(omsCartItem,e);

        // 缓存同步
        flushCartCache(omsCartItem.getMemberId());
    }
}
